#include <QDebug>
#include <QTimer>
#include <QPainter>
#include "astng/ModulesMgr.h"
#include "PyHighlighter.h"
#include "PyEditor.h"

PyEditor::PyEditor(QWidget* parent):
    TextEditor(parent),
    _module(NULL)
{
    connect(this, SIGNAL(contentLoaded()), SLOT(onContentLoaded()));
    QPalette pal = palette();
    pal.setColor(QPalette::Base, Qt::black);
    pal.setColor(QPalette::Text, Qt::white);
    setPalette(pal);

    setFont(QFont("Liberation mono", 11));
    setWordWrapMode(QTextOption::NoWrap);

    _timer = new QTimer(this);
    connect(_timer, SIGNAL(timeout()), SLOT(refresh()));
    _timer->setSingleShot(true);
    _timer->setInterval(50);
}

PyEditor::~PyEditor()
{
    qDebug() << "delete";
    delete _module;
}

void PyEditor::onContentLoaded()
{
    _module = ModulesMgr::instance().moduleByContent(toPlainText(), path);
    connect(document(), SIGNAL(contentsChange(int,int,int)), SLOT(onContenChanged(int, int, int)));
    connect(document(), SIGNAL(blockCountChanged(int)), SLOT(onBlockCountChanged(int)));
    _hight = new PyHighlighter(_module, document());
}

void PyEditor::onContenChanged(int pos, int removed, int added)
{
    //qDebug() << "changed" << pos << removed << added;
    //_module->itemAtPos(pos);
    _module->shiftAst(pos, removed, added);
    _timer->start();
    //qDebug() << "shift ast";
}

void PyEditor::onBlockCountChanged(int)
{
    //qDebug() << "changed";
    _timer->start();
    //refresh();
}

void PyEditor::refresh()
{
    _module->refresh(toPlainText());
    //_hight->rehighlight();
}


